package com.seckill.seckilldemo.controller;

import com.seckill.seckilldemo.pojo.User;
import com.seckill.seckilldemo.service.IGoodsService;
import com.seckill.seckilldemo.service.IUserService;
import com.seckill.seckilldemo.utils.ValidatorUnit;
import com.seckill.seckilldemo.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.Thymeleaf;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    //手动渲染
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    /*@Autowired
    private IUserService userService;*/
    /*@RequestMapping("/toList")
    public String toList(HttpServletResponse response, HttpServletRequest request,HttpSession session, Model model, @CookieValue("userTicket") String ticket){
        if(StringUtils.isEmpty(ticket)){
            return "login";
        }
//        User user = (User) session.getAttribute(ticket);
        User user = userService.getUserByCookie(ticket,request,response);
        if(null == user){
            return "login";
        }
        model.addAttribute("user",user);
        return "goodsList";
    }*/

    //编写UserArgumentResolve
    // 使得不用每次进入controller都要去cookie取值再判断
    //50000
    //window优化前QPS：2720.2/s
    //50000
    //linux优化前QPS：1638.2/s

   /* @RequestMapping("/toList")
    public String toList(Model model,User user){
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        return "goodsList";
    }*/

    //尝试将页面缓存
    @RequestMapping(value = "/toList" , produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,User user,HttpServletRequest request,
                         HttpServletResponse response){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //Redis中拿到前端页面，如果不为空直接返回
        String html = (String) valueOperations.get("goodsList");
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        //为空，手动渲染
        WebContext webContext = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());
        String goodsList = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if(!StringUtils.isEmpty(goodsList)){
            //失效时间1分钟
            valueOperations.set("goodsList",goodsList,60,TimeUnit.SECONDS);
        }
        return goodsList;
    }

    //@PathVariable映射URL中占位符
    /*@RequestMapping("/toDetail/{goodsId}")
    public String toDetail(@PathVariable("goodsId") String goodId,Model model, User user){
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(Long.valueOf(goodId));
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        int seckillStatus = 0;
        int remainSecond = 0;

        if(nowDate.before(startDate)){//秒杀未开始
            remainSecond = (int) ((startDate.getTime() - nowDate.getTime())/1000);
        }else if(nowDate.before(endDate)){//秒杀中
            seckillStatus = 1;
            remainSecond = 0;
        }else{//秒杀结束
            seckillStatus = 2;
            remainSecond = -1;
        }
        model.addAttribute("remainSecond",remainSecond);
        model.addAttribute("seckillStatus",seckillStatus);
        model.addAttribute("goods",goodsVo);
        return "goodsDetail";
    }*/

    //URL缓存
    @RequestMapping(value = "/toDetail/{goodsId}" , produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(@PathVariable("goodsId") String goodId,Model model, User user
            ,HttpServletRequest request, HttpServletResponse response){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + goodId);
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(Long.valueOf(goodId));
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        int seckillStatus = 0;
        int remainSecond = 0;
        if(nowDate.before(startDate)){//秒杀未开始
            remainSecond = (int) ((startDate.getTime() - nowDate.getTime())/1000);
        }else if(nowDate.before(endDate)){//秒杀中
            seckillStatus = 1;
            remainSecond = 0;
        }else{//秒杀结束
            seckillStatus = 2;
            remainSecond = -1;
        }
        model.addAttribute("remainSecond",remainSecond);
        model.addAttribute("seckillStatus",seckillStatus);
        model.addAttribute("goods",goodsVo);
        WebContext webContext = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());
        String goodsDetail = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if(!StringUtils.isEmpty(goodsDetail)){
            valueOperations.set("goodsDetail:"+goodId,goodsDetail,60,TimeUnit.SECONDS);
        }
        return goodsDetail;
    }
}
